package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"pay_srv/models/mysql"
	"pay_srv/models/redis"
	"pay_srv/pkg"

	"pay_srv/internal/svc"
	"pay_srv/pay"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *pay.OrderAddRequest) (*pay.OrderAddResponse, error) {
	// todo: add your logic here and delete this line

	var u mysql.User
	err := mysql.DB.Where("id = ?", in.UserId).First(&u).Error
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if u.Status != 1 {
		return nil, errors.New("状态异常")
	} else {
		//判断商品是否存在
		var g mysql.Goods
		err = g.GetGoodsInfo(int(in.GoodsId))
		if err != nil {
			return nil, errors.New("商品不存在")
		}
		//判断虚拟库存是否充足
		stock := redis.GetGoodsStock(int(in.GoodsId))
		if stock < int64(in.Num) {
			return nil, errors.New("库存不足创建失败")
		}
		orderSn := uuid.NewString()         //订单唯一编号
		amount := g.Price * float64(in.Num) //计算订单的总价数量*商品价格
		o := mysql.Order{
			UserId:  int(in.UserId),
			GoodsId: int(in.GoodsId),
			Num:     int(in.Num),
			OrderSn: orderSn,
			Status:  in.Status,
			PayType: in.PayType,
			Amount:  amount,
		}
		err = o.Add()
		if err != nil {
			return nil, errors.New("订单创建失败")
		}

		price := fmt.Sprintf("%.2f", amount)
		url := pkg.AliPay(orderSn, price) //调用支付宝支付
		return &pay.OrderAddResponse{OrderId: int32(o.ID), PayUrl: url}, nil
	}

}
